//
//  CZNetworkTool.swift
//  微博08
//
//  Created by 1 on 16/3/3.
//  Copyright © 2016年 cjf. All rights reserved.
//

import UIKit
import AFNetworking

// 枚举是值类型
// 类是 指针，引用
enum CZNetworkToolError: Int {
    case AccessTokenEmpty = -1
    case UidEmpty = -2
    
    // 枚举可以有属性
    var errorMessage: String {
        get{
            switch self {
            case AccessTokenEmpty: return "access_token 没有值"
            case UidEmpty: return "Uid 没有值"
            }
        }
    }
    
    // 枚举可以有方法
    func error() -> NSError {
       return NSError(domain: "cn.itcast.net", code: self.rawValue, userInfo: ["errorMessage" : self.errorMessage])
    }
}

class CZNetworkTool: NSObject {
    
    let afnManager: AFHTTPSessionManager
    
    // 单例
    static let sharedInstance: CZNetworkTool = CZNetworkTool()
    
    // private 表示私有方法，除这个文件外的其它类是不知道这个方法的
    private override init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        afnManager = AFHTTPSessionManager(baseURL: baseURL)
        
        // text/plain
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        super.init()
    }
    
    // MARK: - Oauth授权相关
    let client_id = "1736150807"
    let client_secret = "976452e005016d4001af190d0143c6a6"
    let redirect_uri = "http://www.baidu.com/"
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    
    // 获取Oauth授权的登录界面地址
    func oauthLoginUrl() -> NSURL {
        let urlString = oauthUrl + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        return NSURL(string: urlString)!
    }
    
    // 获取Access Token
    func loadAccessToken(code: String, accessTokenFinished:finishedCallBack) {
        // ③.3 请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // ③.4 请求参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        // ③.5 发送POST请求
        afnManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, response) -> Void in
            
            // 网络工具类只负责加载数据，不负责处理数据
            // response as? [String: AnyObject] 表示response有可能转成[String: AnyObject],也可能转不成返回nil
            // response as! [String: AnyObject] 表示response一定能转成[String: AnyObject],如果转不成功，程序崩溃
            let dict = response as? [String: AnyObject]
            // ③.6 获取到数据，调用闭包
            accessTokenFinished(result: dict, error: nil)
            }) { (_, error) -> Void in
                accessTokenFinished(result: nil, error: error)
        }
    }
    
    func loadUserInfo(finished: finishedCallBack) {

        // 守卫 access_Token 可以在后面的代码直接使用，不要放到代码块里面，减少嵌套
//        CZUserAccountViewModel.sharedInstance.userAccount?.access_token = nil
//        guard let access_token = CZUserAccountViewModel.sharedInstance.userAccount?.access_token else {
//
//            let error = CZNetworkToolError.AccessTokenEmpty.error()
//            finished(result: nil, error: error)
//            return
//        }
        
        guard let uid = CZUserAccountViewModel.sharedInstance.userAccount?.uid else {
//            let errorEnem = CZNetworkToolError.UidEmpty
//            let error = NSError(domain: "cn.itcast.net", code: errorEnem.rawValue, userInfo: ["errorMessage" : errorEnem.errorMessage])
            let error = CZNetworkToolError.AccessTokenEmpty.error()
            finished(result: nil, error: error)
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["uid": uid]
    
        // 发送请求
        requestGET(urlString, parameters: parameters, finished: finished)
    }
    
    // 加载微博数据
    func loadStatus(finished: finishedCallBack) {
//        guard let access_token = CZUserAccountViewModel.sharedInstance.userAccount?.access_token else {
//            
//            let error = CZNetworkToolError.AccessTokenEmpty.error()
//            finished(result: nil, error: error)
//            return
//        }
        
        // url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 参数
//        let parameters = ["access_token": access_token]
        
        requestGET(urlString, parameters: nil, finished: finished)
    }
    
    // 定义闭包
    typealias finishedCallBack = (result: [String: AnyObject]?, error: NSError? ) -> ()
    
    private func requestGET(urlString: String, var parameters: [String: AnyObject]?, finished: finishedCallBack) {
        // 守卫 access_Token 可以在后面的代码直接使用，不要放到代码块里面，减少嵌套
        //        CZUserAccountViewModel.sharedInstance.userAccount?.access_token = nil
        guard let access_token = CZUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            
            let error = CZNetworkToolError.AccessTokenEmpty.error()
            finished(result: nil, error: error)
            return
        }
        
        // 当别人没有传入请求参数，创建请求参数
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        // 给参数拼接access_token,添加["access_token": access_token]
        parameters!["access_token"] = access_token
        
        afnManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            finished(result: result as? [String : AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }

    }
}
